package io.sundial.console.taskgroup.web;

import com.google.common.base.Optional;
import io.sundial.console.Pagination;
import io.sundial.console.taskgroup.core.Taskgroup;
import io.sundial.console.taskgroup.service.TaskgroupService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 任务组控制器
 *
 * @author Payne 646742615@qq.com
 * 2019/1/4 16:26
 * @tag 任务
 */
@CrossOrigin
@RestController
@RequestMapping("/api/taskgroup")
public class TaskgroupController {

    @Resource
    private TaskgroupService taskgroupServiceBean;

    /**
     * 新建任务组
     *
     * @param param 任务组对象
     * @return 任务组新建结果
     */
    @PostMapping
    @ResponseBody
    public TaskgroupCreateResult create(@RequestBody @Valid TaskgroupCreateParam param) {
        TaskgroupCreateResult result = new TaskgroupCreateResult();

        Taskgroup taskgroup = new Taskgroup();
        taskgroup.setName(param.getName());
        taskgroup.setPeriod(param.getPeriod());
        taskgroup.setExpression(Optional.fromNullable(param.getExpression()).or(""));
        taskgroup.setDescription(Optional.fromNullable(param.getDescription()).or(""));

        taskgroupServiceBean.save(taskgroup);

        return result;
    }

    /**
     * 分页查询任务组
     *
     * @param param 任务组分页查询参数
     * @return 任务组分页查询结果
     */
    @GetMapping
    @ResponseBody
    public TaskgroupSearchResult search(@Valid TaskgroupSearchParam param) {
        TaskgroupSearchResult result = new TaskgroupSearchResult(param);

        Pagination<Taskgroup> pagination = taskgroupServiceBean.search(param.getPageNo(), param.getPageSize(), param.getKeyword());

        result.setTotal(pagination.getTotal());
        result.setItems(pagination.getItems());

        return result;
    }

    /**
     * 删除任务组
     *
     * @param name  任务组名称
     * @param param 任务组删除参数
     * @return 任务组删除结果
     */
    @DeleteMapping("/{name}")
    @ResponseBody
    public TaskgroupRemoveResult remove(@PathVariable("name") String name, @Valid TaskgroupRemoveParam param) {
        TaskgroupRemoveResult result = new TaskgroupRemoveResult();

        taskgroupServiceBean.remove(name);

        return result;
    }

    /**
     * 更新任务组
     *
     * @param name  任务组名称
     * @param param 任务组对象
     * @return 任务组更新结果
     */
    @PutMapping("/{name}")
    @ResponseBody
    public TaskgroupUpdateResult update(@PathVariable("name") String name, @RequestBody @Valid TaskgroupUpdateParam param) {
        TaskgroupUpdateResult result = new TaskgroupUpdateResult();

        Taskgroup taskgroup = new Taskgroup();

        taskgroup.setName(param.getName());
        taskgroup.setPeriod(param.getPeriod());
        taskgroup.setExpression(Optional.fromNullable(param.getExpression()).or(""));
        taskgroup.setDescription(Optional.fromNullable(param.getDescription()).or(""));

        taskgroupServiceBean.update(name, taskgroup);

        return result;
    }
}
